<template>
  <div class="tinymce-editor">
    <Editor
      ref="editorRef"
      :key="timestamp"
      v-model="myValue"
      :init="init"
      :disabled="disabled"
      @onClick="onClick"
    />
  </div>
</template>
<script>
import axios from 'axios'
import tinymce from 'tinymce/tinymce'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/themes/silver/theme'

import 'tinymce/themes/silver'
import 'tinymce/plugins/image'
import 'tinymce/plugins/media'
import 'tinymce/plugins/table'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/contextmenu'
import 'tinymce/plugins/wordcount'
import 'tinymce/plugins/colorpicker'
import 'tinymce/plugins/textcolor'
import 'tinymce/plugins/preview'
import 'tinymce/plugins/code'
import 'tinymce/plugins/link'
import 'tinymce/plugins/advlist'
import 'tinymce/plugins/codesample'
import 'tinymce/plugins/hr'
import 'tinymce/plugins/fullscreen'
import 'tinymce/plugins/textpattern'
import 'tinymce/plugins/searchreplace'
import 'tinymce/plugins/autolink'
import 'tinymce/plugins/directionality'
import 'tinymce/plugins/visualblocks'
import 'tinymce/plugins/visualchars'
import 'tinymce/plugins/template'
import 'tinymce/plugins/charmap'
import 'tinymce/plugins/nonbreaking'
import 'tinymce/plugins/insertdatetime'
import 'tinymce/plugins/imagetools'
import 'tinymce/plugins/autosave'
import 'tinymce/plugins/autoresize'
import 'tinymce/plugins/print'
import 'tinymce/plugins/save'
import 'tinymce/plugins/anchor'
import 'tinymce/plugins/emoticons'
import 'tinymce/plugins/emoticons/js/emojis'
import 'tinymce/plugins/noneditable'
import 'tinymce/plugins/pagebreak'
import 'tinymce/plugins/paste'
import 'tinymce/plugins/tabfocus'

export default {
  name: 'Tinymce',
  components: {
    Editor
  },
  props: {
    // 传入一个value，使组件支持v-model绑定
    value: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    menubar: { // 菜单栏
      type: String,
      default: 'file edit insert view format table'
    },
    // 相关插件配置
    plugins: {
      type: [String, Array],
      default:
        'advlist charmap anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
    },
    // 工具栏配置
    toolbar: {
      type: [String, Array],
      default:
        'code | undo redo | forecolor backcolor casechange permanentpen removeformat bold italic underline strikethrough link anchor | table insertfile image media pageembed  | alignleft aligncenter alignright alignjustify outdent indent |  numlist bullist checklist | showcomments addcomment |  fullscreen'
      // 'undo redo |  formatselect | fontsizeselect | bold italic underline forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists image table preview'
    },
    // 富文本高度
    height: {
      type: Number,
      default: 500
    }
  },
  data() {
    return {
      uploadUrl: this.domain + '/nt/upload/image',
      // 当前时间戳,是为了解决回显问题
      timestamp: 0,
      // 初始化配置
      init: {
        language_url: '/tinymce/langs/zh_CN.js', // 中文化 默认为英文
        language: 'zh_CN', // 设置富文本编辑器语言
        theme: 'silver', // 主题 必须引入
        skin_url: '/tinymce/skins/ui/oxide',
        selector: '#tinymce', // tinymce的id
        height: this.height,
        plugins: this.plugins,
        toolbar: this.toolbar,
        branding: false,
        menubar: true, // 菜单栏显隐
        toolbar_mode: 'sliding',
        // 如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler
        // 配置了此方法,即可手动选择图片
        images_upload_handler: (blobInfo, success, failure) => {
          const isAccord = blobInfo.blob().type === 'image/jpeg' || blobInfo.blob().type === 'image/png' || blobInfo.blob().type === 'image/GIF' || blobInfo.blob().type === 'image/jpg' || blobInfo.blob().type === 'image/BMP'
          if (blobInfo.blob().size / 1024 / 1024 > 2) {
            failure('上传失败，图片大小请控制在 2M 以内')
          } else if (blobInfo.blob().type === isAccord) {
            failure('图片格式错误')
          } else {
            const formData = new FormData()
            // 服务端接收文件的参数名，文件数据，文件名
            formData.append('file', blobInfo.blob(), blobInfo.filename())
            axios({
              method: 'POST',
              headers: {},
              // 这里是你的上传地址
              url: this.uploadUrl,
              data: formData
            }).then((res) => {
              // 这里返回的是你图片的地址
              success(res.data.data)
            }).catch(() => {
              failure('上传失败')
            })
          }
        },
        resize: false
      },
      myValue: this.value
    }
  },
  watch: {
    value: {
      handler(newValue) {
        this.myValue = newValue
      },
      immediate: true
    },
    myValue(newValue) {
      this.$emit('input', newValue)
    }
  },
  methods: {
    // 需要什么事件可以自己增加 可用的事件参照文档=> https://github.com/tinymce/tinymce-vue
    onClick(e) {
      this.$emit('onClick', e, tinymce)
    },
    // 可以添加一些自己的自定义事件，如清空内容
    clear() {
      this.myValue = ''
    },

    // 解决切换页签后数据回显问题
    setTinymceContent() {
      setTimeout(() => {
        this.timestamp = new Date().getTime()
      }, 10)
    }
  }
}
</script>
